package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.views.ShiftList;
import com.xmy.cultivate.enums.ReadingStatusEnum;
import com.xmy.cultivate.enums.StatusGradeEnum;
import com.xmy.cultivate.exception.CommonException;
import com.xmy.cultivate.mapper.*;
import com.xmy.cultivate.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.CommonUtil;
import com.xmy.cultivate.util.ResultCode;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 学生所在班级与课程 服务实现类
 * </p>
 *
 * @author min
 * @since 2022-08-09
 */
@Service
public class StudentGradeServiceImpl extends ServiceImpl<StudentGradeMapper, StudentGrade> implements IStudentGradeService {

    @Autowired
    @Lazy
    StudentGradeMapper studentGradeMapper;

    @Autowired
    @Lazy
    OrderDetailMapper orderDetailMapper;

    @Autowired
    @Lazy
    GradeMapper gradeMapper;

    @Autowired
    @Lazy
    CourseMapper courseMapper;

    @Autowired
    @Lazy
    IRenewDataService iRenewDataService;

    @Autowired
    @Lazy
    StudentMapper studentMapper;

    @Autowired
    @Lazy
    IStudentGradeService iStudentGradeService;

    @Autowired
    @Lazy
    RecordCourseMapper recordCourseMapper;

    @Autowired
            @Lazy
    IGradeService iGradeService;

    @Autowired
    @Lazy
    IQuarterService iQuarterService;

    @Autowired
    @Lazy
    CourseSchedulingAlwaysMapper courseSchedulingAlwaysMapper;

    final Integer presortResidueCourseCount = 3;//剩余课次大于等于3的算成功

    @Autowired
    @Lazy
    IStaffService iStaffService;


    @Autowired
    @Lazy
    IMqPushService iMqPushService;

    public IPage<ShiftList> findAll(IPage<?> page, Wrapper wrapper) {
        return studentGradeMapper.findAll(page, wrapper);
    }

    public boolean divideClasses(Long orderDetailId, Long gradeId) {

        OrderDetail orderDetail = orderDetailMapper.selectById(orderDetailId);
        if (orderDetail == null) {
            throw new CommonException(ResultCode.ORDERDETAIL_NOT);
        } else if (orderDetail.getResidueCourseCount() <= 0) {
            throw new CommonException(ResultCode.NOR_COURSE);
        }

        Grade grade = gradeMapper.selectById(gradeId);
        if (grade == null) {
            throw new CommonException(ResultCode.GRADE_NOT);
        } else if (grade.getStatus() != StatusGradeEnum.NORMAL) {
            throw new CommonException(ResultCode.KNOTGRADE);
        }

        StudentGrade studentGrade = new StudentGrade();
        studentGrade.setOrderDetailId(orderDetail.getId());
        studentGrade.setStudentId(orderDetail.getStudentId());
        studentGrade.setSchoolId(orderDetail.getSchoolId());
        studentGrade.setGradeId(grade.getId());
        studentGrade.setCourseId(orderDetail.getCourseId());
        studentGrade.setSubjectsId(orderDetail.getSubjectsId());
        studentGrade.setEndDate(grade.getEndDate());

        //studentGrade.setUseCourseCount();
        /*Long renewTeacherId = grade.getTeacherId();
        Integer isRenew = 1;
        //课次
        if((orderDetail.getResidueCourseCount()/orderDetail.getCourseHouse())<3){
            isRenew = 0;
            //应续班老师,为原来的带班老师，待设定
        }else {
            //应续班老师
            studentGrade.setRenewTeacherId(renewTeacherId);
        }*/

        studentGrade.setYearPart(orderDetail.getYearPart());
        studentGrade.setQuarterNum(orderDetail.getQuarterNum());
        studentGrade.setSurplusCourseNum(orderDetail.getResidueCourseCount());
        //studentGrade.setIsRenew(isRenew);
        Integer rs = studentGradeMapper.insert(studentGrade);
        Course course = courseMapper.selectById(grade.getCourseId());

        //更新续班里的老师
        iRenewDataService.updateTeacher(grade.getSchoolId(), orderDetail.getStudentId(), course, grade);


        return rs > 0 ? true : false;
        //return  studentGradeMapper.divideClasses(Long orderDetailId,Long gradeId);
    }

    /**
     * 调班
     *
     * @param paramStudentGrade
     * @return
     */
    @Transactional
    public boolean melodyClass(StudentGrade paramStudentGrade) {
        return true;
    }


    public boolean addData(Long orderDetailId, Long schoolId, Long studentId, Long gradeId, Long courseId, Long subjectsId, Integer yearPart, Integer quarterNum, Integer surplusCourseNum) {
        StudentGrade studentGrade = new StudentGrade();
        studentGrade.setOrderDetailId(orderDetailId);
        studentGrade.setSchoolId(schoolId);
        studentGrade.setStudentId(studentId);
        studentGrade.setGradeId(gradeId);
        studentGrade.setCourseId(courseId);
        studentGrade.setSubjectsId(subjectsId);
        studentGrade.setYearPart(yearPart);
        studentGrade.setQuarterNum(quarterNum);
        studentGrade.setSurplusCourseNum(surplusCourseNum);
        studentGradeMapper.insert(studentGrade);
        return true;
    }

    /**
     * 学生在班级的状态
     *
     * @return
     */
    public String studentAtGradeState(Long gradeId, Long studentId, Integer reType) {
        Student student = studentMapper.selectById(studentId);
        QueryWrapper<StudentGrade> studentGradeQueryWrapperForStudent = new QueryWrapper<>();
        studentGradeQueryWrapperForStudent.orderByDesc("created_at");
        studentGradeQueryWrapperForStudent.eq("deleted", 0);
        studentGradeQueryWrapperForStudent.eq("grade_id", gradeId);
        studentGradeQueryWrapperForStudent.eq("student_id", student.getId());
        studentGradeQueryWrapperForStudent.ne("status", 3);
        studentGradeQueryWrapperForStudent.last("limit 1");
        StudentGrade studentGrade = studentGradeMapper.selectOne(studentGradeQueryWrapperForStudent);
        String state = "";
        if (studentGrade != null) {
            if (reType == null || reType == 1) {
                state = studentGrade.getReadingStatus().getValue();
            } else if (reType == 2) {
                state = studentGrade.getReadingStatus().getKey().toString();
            }
        }
        return state;
    }

    /**
     * 学生在班级的状态
     *
     * @return
     */
    public String getCourseStatus(Long gradeId, Long studentId, Integer reType) {
        Student student = studentMapper.selectById(studentId);
        QueryWrapper<StudentGrade> studentGradeQueryWrapperForStudent = new QueryWrapper<>();
        studentGradeQueryWrapperForStudent.orderByDesc("created_at");
        studentGradeQueryWrapperForStudent.eq("deleted", 0);
        studentGradeQueryWrapperForStudent.eq("grade_id", gradeId);
        studentGradeQueryWrapperForStudent.eq("student_id", student.getId());
        studentGradeQueryWrapperForStudent.ne("status", 3);
        studentGradeQueryWrapperForStudent.last("limit 1");
        StudentGrade studentGrade = studentGradeMapper.selectOne(studentGradeQueryWrapperForStudent);
        String state = studentGrade.getCourseStatus().toString();
        return state;
    }


    /**
     * 学生在班级的状态
     *
     * @return
     */
    public String studentAtGradeStateForOrderDetailId(Long orderDetailId, Long studentId, Integer reType) {
        Student student = studentMapper.selectById(studentId);
        QueryWrapper<StudentGrade> studentGradeQueryWrapperForStudent = new QueryWrapper<>();
        studentGradeQueryWrapperForStudent.orderByDesc("created_at");
        studentGradeQueryWrapperForStudent.eq("deleted", 0);
        studentGradeQueryWrapperForStudent.eq("order_detail_id", orderDetailId);
        studentGradeQueryWrapperForStudent.eq("student_id", student.getId());
        studentGradeQueryWrapperForStudent.ne("status", 3);
        studentGradeQueryWrapperForStudent.last("limit 1");
        StudentGrade studentGrade = studentGradeMapper.selectOne(studentGradeQueryWrapperForStudent);
        String state = "";
        if (studentGrade != null) {
            if (reType == null || reType == 1) {
                state = studentGrade.getReadingStatus().getValue();
            } else if (reType == 2) {
                state = studentGrade.getReadingStatus().getKey().toString();
            }
        }
        return state;
    }

    /**
     * 结课
     *
     * @param studentGrade
     * @return
     */
    public boolean finishCourse(StudentGrade studentGrade) {

        Grade gradeInfo = gradeMapper.selectById(studentGrade.getGradeId());
        Long studentId = studentGrade.getStudentId();
        Long gradeId = studentGrade.getGradeId();

        if (gradeInfo != null) {
            if (gradeInfo.getStatus().getKey().equals(1)) {
                Student student = studentMapper.selectById(studentId);
                QueryWrapper<StudentGrade> studentGradeQueryWrapperForStudent = new QueryWrapper<>();
                studentGradeQueryWrapperForStudent.orderByDesc("created_at");
                studentGradeQueryWrapperForStudent.eq("deleted", 0);
                studentGradeQueryWrapperForStudent.eq("grade_id", gradeId);
                studentGradeQueryWrapperForStudent.eq("student_id", student.getId());
                studentGradeQueryWrapperForStudent.ne("status", 3);
                studentGradeQueryWrapperForStudent.eq("reading_status", 1);
                //studentGradeQueryWrapperForStudent.last("limit 1");
                List<StudentGrade> studentGradeList = studentGradeMapper.selectList(studentGradeQueryWrapperForStudent);
                for (StudentGrade studentGradeItem : studentGradeList) {
                    studentGradeItem.setReadingStatus(ReadingStatusEnum.FINISH);
                    studentGradeMapper.updateById(studentGradeItem);
                }
                return true;
            } else {
                return false;
            }
        } else {
            throw new CommonException(ResultCode.NOTDATA);
        }
    }

    /**
     * 停课
     *
     * @param studentGrade
     * @return
     */
    @Override
    public boolean stopGrade(StudentGrade studentGrade) {
        Grade gradeInfo = gradeMapper.selectById(studentGrade.getGradeId());
        Long studentId = studentGrade.getStudentId();
        Long gradeId = studentGrade.getGradeId();

        if (gradeInfo != null) {
            if (gradeInfo.getStatus().getKey().equals(1)) {
                Student student = studentMapper.selectById(studentId);
                QueryWrapper<StudentGrade> studentGradeQueryWrapperForStudent = new QueryWrapper<>();
                studentGradeQueryWrapperForStudent.orderByDesc("created_at");
                studentGradeQueryWrapperForStudent.eq("deleted", 0);
                studentGradeQueryWrapperForStudent.eq("grade_id", gradeId);
                studentGradeQueryWrapperForStudent.eq("student_id", student.getId());
                studentGradeQueryWrapperForStudent.ne("status", 3);
                studentGradeQueryWrapperForStudent.eq("reading_status", 1);

                //studentGradeQueryWrapperForStudent.last("limit 1");
                List<StudentGrade> studentGradeList = studentGradeMapper.selectList(studentGradeQueryWrapperForStudent);
                for (StudentGrade studentGradeItem : studentGradeList) {
                    studentGradeItem.setReadingStatus(ReadingStatusEnum.STOP);
                    studentGradeItem.setStopCourseDate(LocalDate.now());
                    studentGradeMapper.updateById(studentGradeItem);
                }
                return true;
            } else {
                return false;
            }
        } else {
            throw new CommonException(ResultCode.NOTDATA);
        }
    }


    /**
     * 复课
     *
     * @param studentGrade
     * @return
     */
    @Override
    public boolean agrainGrade(StudentGrade studentGrade) {
        Grade gradeInfo = gradeMapper.selectById(studentGrade.getGradeId());
        Long studentId = studentGrade.getStudentId();
        Long gradeId = studentGrade.getGradeId();

        if (gradeInfo != null) {
            if (gradeInfo.getStatus().getKey().equals(1)) {
                Student student = studentMapper.selectById(studentId);
                QueryWrapper<StudentGrade> studentGradeQueryWrapperForStudent = new QueryWrapper<>();
                studentGradeQueryWrapperForStudent.orderByDesc("created_at");
                studentGradeQueryWrapperForStudent.eq("deleted", 0);
                studentGradeQueryWrapperForStudent.eq("grade_id", gradeId);
                studentGradeQueryWrapperForStudent.eq("student_id", student.getId());
                studentGradeQueryWrapperForStudent.ne("status", 3);
                studentGradeQueryWrapperForStudent.eq("reading_status", 4);
                //studentGradeQueryWrapperForStudent.last("limit 1");
                List<StudentGrade> studentGradeList = studentGradeMapper.selectList(studentGradeQueryWrapperForStudent);
                for (StudentGrade studentGradeItem : studentGradeList) {
                    studentGradeItem.setReadingStatus(ReadingStatusEnum.IN_READING);
                    studentGradeMapper.updateById(studentGradeItem);
                }
                return true;
            } else {
                return false;
            }
        } else {
            throw new CommonException(ResultCode.NOTDATA);
        }
    }

    @Override
    public boolean courseStatusChange(StudentGrade studentGrade) {

        String courseStatus = iStudentGradeService.getCourseStatus(studentGrade.getGradeId(), studentGrade.getStudentId(), 1);

        Grade gradeInfo = gradeMapper.selectById(studentGrade.getGradeId());
        Long studentId = studentGrade.getStudentId();
        Long gradeId = studentGrade.getGradeId();

        if (gradeInfo != null) {
            if (gradeInfo.getStatus().getKey().equals(1)) {
                Student student = studentMapper.selectById(studentId);
                QueryWrapper<StudentGrade> studentGradeQueryWrapperForStudent = new QueryWrapper<>();
                studentGradeQueryWrapperForStudent.orderByDesc("created_at");
                studentGradeQueryWrapperForStudent.eq("deleted", 0);
                studentGradeQueryWrapperForStudent.eq("grade_id", gradeId);
                studentGradeQueryWrapperForStudent.eq("student_id", student.getId());
                studentGradeQueryWrapperForStudent.ne("status", 3);
                studentGradeQueryWrapperForStudent.eq("course_status", courseStatus);
                //studentGradeQueryWrapperForStudent.last("limit 1");
                List<StudentGrade> studentGradeList = studentGradeMapper.selectList(studentGradeQueryWrapperForStudent);
                if (courseStatus.equals("1")) {
                    courseStatus = "0";
                } else {
                    courseStatus = "1";
                }
                for (StudentGrade studentGradeItem : studentGradeList) {
                    studentGradeItem.setCourseStatus(Integer.parseInt(courseStatus));
                    studentGradeMapper.updateById(studentGradeItem);
                }
                return true;
            } else {
                return false;
            }
        } else {
            throw new CommonException(ResultCode.NOTDATA);
        }
    }

    @Override
    public boolean finishCourseForOrder(StudentGrade studentGrade) {

        //OrderDetail orderDetail = orderDetailMapper.selectById(studentGrade.getOrderDetailId());
        QueryWrapper<StudentGrade> studentGradeQueryWrapperForStudent = new QueryWrapper<>();
        studentGradeQueryWrapperForStudent.orderByDesc("created_at");
        studentGradeQueryWrapperForStudent.eq("deleted", 0);
        studentGradeQueryWrapperForStudent.eq("order_detail_id", studentGrade.getOrderDetailId());
        studentGradeQueryWrapperForStudent.eq("student_id", studentGrade.getStudentId());
        studentGradeQueryWrapperForStudent.ne("status", 3);
        studentGradeQueryWrapperForStudent.eq("reading_status", 1);
        //studentGradeQueryWrapperForStudent.last("limit 1");
        List<StudentGrade> studentGradeList = studentGradeMapper.selectList(studentGradeQueryWrapperForStudent);
        boolean rs = false;
        for (StudentGrade studentGradeItem : studentGradeList) {
            Grade gradeInfo = gradeMapper.selectById(studentGradeItem.getGradeId());
            if (gradeInfo != null) {
                if (gradeInfo.getStatus().getKey().equals(1)) {
                    studentGradeItem.setReadingStatus(ReadingStatusEnum.FINISH);
                    studentGradeMapper.updateById(studentGradeItem);
                    rs = true;
                }
            }
        }
        return rs;
    }

    @Override
    public boolean stopGradeForOrder(StudentGrade studentGrade) {
        QueryWrapper<StudentGrade> studentGradeQueryWrapperForStudent = new QueryWrapper<>();
        studentGradeQueryWrapperForStudent.orderByDesc("created_at");
        studentGradeQueryWrapperForStudent.eq("deleted", 0);
        studentGradeQueryWrapperForStudent.eq("order_detail_id", studentGrade.getOrderDetailId());
        studentGradeQueryWrapperForStudent.eq("student_id", studentGrade.getStudentId());
        studentGradeQueryWrapperForStudent.ne("status", 3);
        studentGradeQueryWrapperForStudent.eq("reading_status", 1);
        //studentGradeQueryWrapperForStudent.last("limit 1");
        List<StudentGrade> studentGradeList = studentGradeMapper.selectList(studentGradeQueryWrapperForStudent);
        boolean rs = false;
        for (StudentGrade studentGradeItem : studentGradeList) {
            Grade gradeInfo = gradeMapper.selectById(studentGradeItem.getGradeId());
            if (gradeInfo != null) {
                if (gradeInfo.getStatus().getKey().equals(1)) {
                    studentGradeItem.setReadingStatus(ReadingStatusEnum.STOP);
                    studentGradeItem.setStopCourseDate(LocalDate.now());
                    studentGradeMapper.updateById(studentGradeItem);
                    rs = true;
                }
            }
        }
        return rs;
    }

    @Override
    public boolean agrainGradeForOrder(StudentGrade studentGrade) {
        QueryWrapper<StudentGrade> studentGradeQueryWrapperForStudent = new QueryWrapper<>();
        studentGradeQueryWrapperForStudent.orderByDesc("created_at");
        studentGradeQueryWrapperForStudent.eq("deleted", 0);
        studentGradeQueryWrapperForStudent.eq("order_detail_id", studentGrade.getOrderDetailId());
        studentGradeQueryWrapperForStudent.eq("student_id", studentGrade.getStudentId());
        studentGradeQueryWrapperForStudent.ne("status", 3);
        studentGradeQueryWrapperForStudent.eq("reading_status", 4);
        //studentGradeQueryWrapperForStudent.last("limit 1");
        List<StudentGrade> studentGradeList = studentGradeMapper.selectList(studentGradeQueryWrapperForStudent);
        boolean rs = false;
        for (StudentGrade studentGradeItem : studentGradeList) {
            Grade gradeInfo = gradeMapper.selectById(studentGradeItem.getGradeId());
            if (gradeInfo != null) {
                if (gradeInfo.getStatus().getKey().equals(1)) {
                    studentGradeItem.setReadingStatus(ReadingStatusEnum.IN_READING);
                    studentGradeMapper.updateById(studentGradeItem);
                    rs = true;
                }
            }
        }
        return rs;
    }

    /**
     * 获取本学期使用课时
     *
     * @param yearPart
     * @param quarterNum
     * @param subjectsId
     * @param schoolId
     * @param studentId
     * @return
     */
    @Override
    public Long getStudentUseCourseCount(Integer yearPart, Integer quarterNum, Long schoolId, Long subjectsId, Long studentId, Integer lessonType,Integer yearClassId) {
        /*QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
        studentGradeQueryWrapper.eq("t1.year_part", yearPart);
        studentGradeQueryWrapper.eq("t1.quarter_num", quarterNum);
        studentGradeQueryWrapper.eq("t1.subjects_id", subjectsId);
        studentGradeQueryWrapper.eq("t1.student_id", studentId);
        studentGradeQueryWrapper.eq("t1.lesson_type", lessonType);
        studentGradeQueryWrapper.ne("t1.status", 3);//不等于订单作废的
        studentGradeQueryWrapper.eq("t1.deleted", 0);
        studentGradeQueryWrapper.eq("t2.is_makeup", 0);//非补课班*/
        return studentGradeMapper.getStudentUseCourseCount(yearPart,quarterNum,subjectsId,studentId,lessonType,yearClassId);
    }

    /**
     * 获取最后一次后班数据
     *
     * @param schoolId
     * @param studentId
     * @param subjectsId
     * @param yearPart
     * @param quaterNum
     * @return
     */
    public StudentGrade getLastStudentGradeForOrderDetailId(Long schoolId, Long studentId, Long subjectsId, Integer yearPart, Integer quaterNum, Integer lessonType) {
        StudentGrade studentGrade = this.getStudentGradeForOrderDetailIdOne(schoolId, studentId, subjectsId, yearPart, quaterNum, 1, lessonType);
        if (studentGrade == null) {
            studentGrade = this.getStudentGradeForOrderDetailIdOne(schoolId, studentId, subjectsId, yearPart, quaterNum, 5, lessonType);
        }
        if (studentGrade == null) {
            studentGrade = this.getStudentGradeForOrderDetailIdOne(schoolId, studentId, subjectsId, yearPart, quaterNum, 6, lessonType);
        }
        if (studentGrade == null) {
            studentGrade = this.getStudentGradeForOrderDetailIdOne(schoolId, studentId, subjectsId, yearPart, quaterNum, 4, lessonType);
        }
        if (studentGrade == null) {
            studentGrade = this.getStudentGradeForOrderDetailIdOne(schoolId, studentId, subjectsId, yearPart, quaterNum, 2, lessonType);
        }
        return studentGrade;
    }

    public StudentGrade getStudentGradeForOrderDetailIdOne(Long schoolId, Long studentId, Long subjectsId, Integer yearPart, Integer quaterNum, Integer readingStatus, Integer lessonType) {
        QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
        studentGradeQueryWrapper.eq("year_part", yearPart);
        studentGradeQueryWrapper.eq("quarter_num", quaterNum);
        studentGradeQueryWrapper.eq("subjects_id", subjectsId);
        studentGradeQueryWrapper.eq(schoolId != null, "school_id", schoolId);
        studentGradeQueryWrapper.eq("student_id", studentId);
        studentGradeQueryWrapper.eq("reading_status", readingStatus);
        studentGradeQueryWrapper.eq("lesson_type", lessonType);
        //studentGradeQueryWrapper.eq("reading_status",1);
        studentGradeQueryWrapper.last("limit 1");
        studentGradeQueryWrapper.orderByDesc("id", "created_at");
        StudentGrade studentGrade = iStudentGradeService.getOne(studentGradeQueryWrapper);
        return studentGrade;
    }

/*
    @Override
    public void updateIsPresort(Long schoolId, Long studentId, Integer yearPart, Integer quarterNum, Long subjectsId, Integer lessonType) {
        Integer yearPartAndQuarter = Integer.parseInt(yearPart + "" + quarterNum);
        Integer residueCount = orderDetailMapper.getResidueCourseCount(schoolId, studentId, subjectsId, yearPartAndQuarter, lessonType);
        Quarter nextQuarter = CommonUtil.getNextQuarter(yearPart, quarterNum);

        Integer nextYearPart = nextQuarter.getYearPart();
        Integer nextQuarterNum = nextQuarter.getNum();

        //为了获取年级信息
        OrderDetail lastOrderDetail = orderDetailMapper.getLastOneForStudent(yearPart, quarterNum, studentId, subjectsId, lessonType);

        Integer gradeSection = CommonUtil.getGradeSection(lastOrderDetail.getYearClassId());
        CourseSchedulingAlways courseSchedulingAlways = courseSchedulingAlwaysMapper.getOneForDate(LocalDate.now(), gradeSection);
        if (courseSchedulingAlways != null) {
            if (courseSchedulingAlways.getNum() <= 3) {
                nextYearPart = yearPart;
                nextQuarterNum = quarterNum;
            }

            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
            studentGradeQueryWrapper.eq("year_part", nextYearPart);
            studentGradeQueryWrapper.eq("quarter_num", nextQuarterNum);
            studentGradeQueryWrapper.eq("subjects_id", subjectsId);
            studentGradeQueryWrapper.eq("student_id", studentId);
            if (residueCount < 3) {
                studentGradeQueryWrapper.eq("is_presort", 1);
                List<StudentGrade> studentGradeList = this.list(studentGradeQueryWrapper);
                for (StudentGrade studentGrade : studentGradeList) {
                    studentGrade.setIsPresort(2);
                    studentGrade.setRemark("课时小于等于3，" + "时间：" + LocalDateTime.now().withNano(0));
                    this.updateById(studentGrade);
                }
            } else {
                studentGradeQueryWrapper.ne("is_presort", 1);
                List<StudentGrade> studentGradeList = this.list(studentGradeQueryWrapper);
                for (StudentGrade studentGrade : studentGradeList) {
                    studentGrade.setIsPresort(1);
                    studentGrade.setRemark("课时大于3，" + "时间：" + LocalDateTime.now().withNano(0));
                    this.updateById(studentGrade);
                }
            }
        }
    }

    @Async
    public void updatePerse(CourseSchedulingDetail courseSchedulingDetail, Quarter quarterNow) {
        try {
            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
            Integer yearAndQuarter = Integer.parseInt(quarterNow.getYearPart()+""+quarterNow.getNum());
            if (courseSchedulingDetail.getLessonNum() <= 3) {
                //计算的是当前学期的
                //List<Integer> yearClassIdList = CommonUtil.getYearClassIdForGradeSection(CourseSchedulingDetail.getGradeSection());
                studentGradeQueryWrapper.eq("grade_id", courseSchedulingDetail.getGradeId());
                List<StudentGrade> studentGradeList = this.list(studentGradeQueryWrapper);
                for (StudentGrade studentGrade : studentGradeList) {
                    Integer allCourseCount = orderDetailMapper.getAllCourseCountForSubjects(studentGrade.getSchoolId(), studentGrade.getStudentId(), studentGrade.getSubjectsId(), yearAndQuarter, studentGrade.getLessonType());
                    if (allCourseCount >= 3) {
                        Integer count = recordCourseMapper.getRecordCountArrive(studentGrade.getYearPart(), studentGrade.getQuarterNum(), studentGrade.getStudentId());
                        if (count > 0) {
                            if (studentGrade.getIsPresort().equals(1)) {
                                studentGrade.setIsPresort(2);//预分班续报成功
                            } else {
                                studentGrade.setIsPresort(3);//没有添加到预分班的续报成功
                            }
                        } else {
                            if (allCourseCount == 3) {
                                studentGrade.setIsPresort(4);
                            }
                        }
                        this.updateById(studentGrade);
                    }
                }
            } else if (courseSchedulingDetail.getLessonNum() >= 12) {
                //计算的是下个学期的
                Quarter quarterNext = CommonUtil.getNextQuarter(quarterNow.getYearPart(), quarterNow.getNum());
                studentGradeQueryWrapper.eq("year_part", courseSchedulingDetail.getYearPart());
                studentGradeQueryWrapper.eq("quarter_num", courseSchedulingDetail.getQuarter());
                studentGradeQueryWrapper.eq("lesson_type", 1);
                //studentGradeQueryWrapper.notIn("is_presort",2,3);
                studentGradeQueryWrapper.eq("grade_id", courseSchedulingDetail.getGradeId());
                List<StudentGrade> studentGradeList = this.list(studentGradeQueryWrapper);
                for (StudentGrade studentGrade : studentGradeList) {
                    studentGradeQueryWrapper.clear();
                    studentGradeQueryWrapper.eq("year_part", quarterNext.getYearPart());
                    studentGradeQueryWrapper.eq("quarter_num", quarterNext.getNum());
                    studentGradeQueryWrapper.eq("student_id", studentGrade.getStudentId());
                    studentGradeQueryWrapper.eq("lesson_type", studentGrade.getLessonType());
                    studentGradeQueryWrapper.eq("subjects_id", studentGrade.getSubjectsId());
                    List<StudentGrade> studentGradeListNext = this.list(studentGradeQueryWrapper);
                    for (StudentGrade studentGradeNext : studentGradeListNext) {
                        //获取到前学期及后面学期的剩余课次
                        Integer residueCourseCount = orderDetailMapper.getResidueCourseCount(studentGradeNext.getSchoolId(), studentGradeNext.getStudentId(), studentGradeNext.getSubjectsId(), yearAndQuarter, studentGradeNext.getLessonType());
                        //小于3次课从预分班中删除
                        if (residueCourseCount < 3) {
                            studentGradeNext.setIsPresort(4);
                            this.updateById(studentGradeNext);
                            this.removeById(studentGradeNext.getId());
                        }
                    }

                }
            }
        } catch (Exception e) {
        }
    }
*/

    @Override
    public void updateStudentIsPresort() {

        Quarter quarterNow = iQuarterService.getNowQuarter();

        Integer yearPart = quarterNow.getYearPart();
        Integer quarterNum = quarterNow.getNum();
        LocalDate localDate = LocalDate.now();
        localDate = localDate.minusDays(1);//由于是零晨3点更新，所以要减一天

        //第3次课之前的计算当前学期
        CourseSchedulingAlways courseSchedulingAlwaysFive = courseSchedulingAlwaysMapper.getOneForNum(yearPart, quarterNum, 3);

        if (courseSchedulingAlwaysFive != null && !localDate.isAfter(courseSchedulingAlwaysFive.getEndDate())) {
            //log.error("进入当前学期");
            //QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
            //recordCourseQueryWrapper.eq("year_part", yearPart);
            //recordCourseQueryWrapper.eq("quarter", quarterNum);
            //recordCourseQueryWrapper.eq("school_date", localDate);
            //recordCourseQueryWrapper.eq("lesson_type", 1);
            //recordCourseQueryWrapper.eq("is_deduct_house", 1);
            //recordCourseQueryWrapper.eq("status", 1);
            //recordCourseQueryWrapper.groupBy("student_id","subjects_id");
            //recordCourseQueryWrapper.eq("student_id", 1601062777894469632L);
            Integer rCount = 3;//已经扣大于等于3课次的学生
            List<RecordCourse> recordCourseList = recordCourseMapper.getRecordCourseCount(yearPart,quarterNum,1,rCount);
            //log.error("recordCourseList:" + recordCourseList.size());
            for (RecordCourse recordCourse : recordCourseList) {
                try {
                    //上面已经做了时间限制，这里取消
                    /*if (recordCourse.getLessonNum() != null && recordCourse.getLessonNum() <= 3) {
                    }*/
                    //这里算总的课次
                    Integer allCourseCount = orderDetailMapper.getAllCourseCountForSubjects(null,recordCourse.getStudentId(), recordCourse.getSubjectsId(), recordCourse.getYearAndQuarter(), 1);
                    if (allCourseCount >= this.presortResidueCourseCount) {
                        //还没有添加过续报信息
                        Integer presortCount = studentGradeMapper.getPresortCount(yearPart,quarterNum,recordCourse.getSubjectsId(),recordCourse.getStudentId(),recordCourse.getLessonType(),"1,2,3");
                        if (presortCount == 0){
                            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                            studentGradeQueryWrapper.eq("year_part", yearPart);
                            studentGradeQueryWrapper.eq("quarter_num", quarterNum);
                            studentGradeQueryWrapper.eq("student_id", recordCourse.getStudentId());
                            studentGradeQueryWrapper.eq("subjects_id", recordCourse.getSubjectsId());
                            studentGradeQueryWrapper.eq("lesson_type", recordCourse.getLessonType());
                            studentGradeQueryWrapper.eq("status", 1);
                            studentGradeQueryWrapper.orderByDesc("id");
                            studentGradeQueryWrapper.last("limit 1");
                            List<StudentGrade> studentGradeList = this.list(studentGradeQueryWrapper);
                            for (StudentGrade studentGrade : studentGradeList) {
                                studentGrade.setIsPresort(3);
                                studentGrade.setRemark("课次大于等于3，" + "时间：" + LocalDateTime.now().withNano(0));
                                studentGrade.setCreatedAt(LocalDateTime.now().withNano(0));//修改添加时间
                                this.updateById(studentGrade);
                            }
                        }else {
                            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                            studentGradeQueryWrapper.eq("year_part", yearPart);
                            studentGradeQueryWrapper.eq("quarter_num", quarterNum);
                            studentGradeQueryWrapper.eq("student_id", recordCourse.getStudentId());
                            studentGradeQueryWrapper.eq("subjects_id", recordCourse.getSubjectsId());
                            studentGradeQueryWrapper.eq("lesson_type", recordCourse.getLessonType());
                            studentGradeQueryWrapper.eq("status", 1);
                            studentGradeQueryWrapper.in("is_presort",1,2,3);
                            studentGradeQueryWrapper.orderByDesc("id");
                            studentGradeQueryWrapper.last("limit 1");
                            List<StudentGrade> studentGradeList = this.list(studentGradeQueryWrapper);
                            for (StudentGrade studentGrade : studentGradeList) {
                                if (studentGrade.getIsPresort().equals(1)) {
                                    studentGrade.setIsPresort(2);//预分班续报成功
                                    this.updateById(studentGrade);
                                } else {
                                    studentGrade.setIsPresort(3);//没有添加预分班的，续报成功
                                    this.updateById(studentGrade);
                                }
                            }
                        }
                    } else {
                        QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                        studentGradeQueryWrapper.eq("year_part", yearPart);
                        studentGradeQueryWrapper.eq("quarter_num", quarterNum);
                        studentGradeQueryWrapper.eq("student_id", recordCourse.getStudentId());
                        studentGradeQueryWrapper.eq("subjects_id", recordCourse.getSubjectsId());
                        studentGradeQueryWrapper.eq("lesson_type", recordCourse.getLessonType());
                        studentGradeQueryWrapper.eq("status", 1);
                        studentGradeQueryWrapper.in("is_presort", 1);
                        List<StudentGrade> studentGradeList = this.list(studentGradeQueryWrapper);
                        for (StudentGrade studentGrade : studentGradeList) {
                            studentGrade.setRemark("小于3次课，续报失败");
                            studentGrade.setIsPresort(4);
                            this.updateById(studentGrade);
                        }
                    }
                } catch (Exception e) {
                }
            }

        }

        //第10次课之后的处理下一个学期预分班
        CourseSchedulingAlways courseSchedulingAlwaysTen = courseSchedulingAlwaysMapper.getOneForNum(yearPart, quarterNum, 10);

        if (courseSchedulingAlwaysTen != null && courseSchedulingAlwaysTen.getEndDate().isBefore(localDate)) {
            //log.error("进入下一学期");
            Quarter quarterNext = CommonUtil.getNextQuarter(yearPart, quarterNum);
            Integer yearAndQuarter = Integer.parseInt(quarterNow.getYearPart() + "" + quarterNow.getNum());
            //获取预分班学生信息
            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
            studentGradeQueryWrapper.in("is_presort", 1,4);//把失败的也找查出来，如果又续费了把状态改回去
            studentGradeQueryWrapper.eq("year_part", quarterNext.getYearPart());
            studentGradeQueryWrapper.eq("quarter_num", quarterNext.getNum());
            studentGradeQueryWrapper.eq("lesson_type",1);
            List<StudentGrade> studentGradeList = this.list(studentGradeQueryWrapper);
            for (StudentGrade studentGrade : studentGradeList) {
                try {
                    //剩余课次
                    Integer residueCourseCount = orderDetailMapper.getResidueCourseCountNotSchoolId(studentGrade.getStudentId(), studentGrade.getSubjectsId(), yearAndQuarter, 1);
                    if (studentGrade.getIsPresort().equals(1)){
                        if (residueCourseCount > 0 && residueCourseCount < this.presortResidueCourseCount) {
                            /**Integer count = studentGradeMapper.getIsPresortCount(studentGrade.getYearPart(),studentGrade.getQuarterNum(),studentGrade.getSchoolId(),studentGrade.getSubjectsId(),studentGrade.getStudentId());
                             if (count>0){

                             }*/
                            studentGrade.setIsPresort(4);
                            studentGrade.setRemark("小于3课次，续报失败");
                            this.updateById(studentGrade);
                        } else if (residueCourseCount.equals(0)) {
                            studentGrade.setIsPresort(4);
                            studentGrade.setRemark("剩余0课次，续报失败");
                            this.updateById(studentGrade);
                        /*if (studentGrade.getUseCourseCount().equals(0)){
                            UpdateWrapper<StudentGrade> studentGradeUpdateWrapper = new UpdateWrapper<>();
                            studentGradeUpdateWrapper.eq("id",studentGrade.getId());
                            studentGradeUpdateWrapper.set("deleted",1);
                            iStudentGradeService.update(studentGradeUpdateWrapper);
                        }*/
                            //this.removeById(studentGrade.getId());
                        }
                    }else if (studentGrade.getIsPresort().equals(4)){
                        if (residueCourseCount>=this.presortResidueCourseCount){
                            studentGrade.setIsPresort(1);
                            studentGrade.setRemark("课次大于3恢复续报率状态");
                            studentGrade.setCreatedAt(LocalDateTime.now().withNano(0));
                            this.updateById(studentGrade);
                        }
                    }
                } catch (Exception e) {
                }
            }
        }

        Integer rCount = 15;//已经扣大于等于15课次的学生
        List<RecordCourse> recordCourseList = recordCourseMapper.getRecordCourseCount(yearPart,quarterNum,1,rCount);
        //log.error("recordCourseList:" + recordCourseList.size());
        for (RecordCourse recordCourse : recordCourseList) {
            try {
                //还没有添加过续报信息
                Integer presortCount = studentGradeMapper.getPresortCount(yearPart,quarterNum,recordCourse.getSubjectsId(),recordCourse.getStudentId(),recordCourse.getLessonType(),"1,2,3");
                if (presortCount == 0){
                    QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                    studentGradeQueryWrapper.eq("year_part", yearPart);
                    studentGradeQueryWrapper.eq("quarter_num", quarterNum);
                    studentGradeQueryWrapper.eq("student_id", recordCourse.getStudentId());
                    studentGradeQueryWrapper.eq("subjects_id", recordCourse.getSubjectsId());
                    studentGradeQueryWrapper.eq("lesson_type", recordCourse.getLessonType());
                    studentGradeQueryWrapper.eq("status", 1);
                    studentGradeQueryWrapper.orderByDesc("id");
                    studentGradeQueryWrapper.last("limit 1");
                    List<StudentGrade> studentGradeList = this.list(studentGradeQueryWrapper);
                    for (StudentGrade studentGrade : studentGradeList) {
                        studentGrade.setIsPresort(3);
                        studentGrade.setRemark("已上大于等于15，" + "时间：" + LocalDateTime.now().withNano(0));
                        studentGrade.setCreatedAt(LocalDateTime.now().withNano(0));//修改添加时间
                        this.updateById(studentGrade);
                    }
                }else {
                    QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                    studentGradeQueryWrapper.eq("year_part", yearPart);
                    studentGradeQueryWrapper.eq("quarter_num", quarterNum);
                    studentGradeQueryWrapper.eq("student_id", recordCourse.getStudentId());
                    studentGradeQueryWrapper.eq("subjects_id", recordCourse.getSubjectsId());
                    studentGradeQueryWrapper.eq("lesson_type", recordCourse.getLessonType());
                    studentGradeQueryWrapper.eq("status", 1);
                    studentGradeQueryWrapper.in("is_presort",1,2,3);
                    studentGradeQueryWrapper.orderByDesc("id");
                    studentGradeQueryWrapper.last("limit 1");
                    List<StudentGrade> studentGradeList = this.list(studentGradeQueryWrapper);
                    for (StudentGrade studentGrade : studentGradeList) {
                        if (studentGrade.getIsPresort().equals(1)) {
                            studentGrade.setIsPresort(2);//预分班续报成功
                            this.updateById(studentGrade);
                        } else {
                            studentGrade.setIsPresort(3);//没有添加预分班的，续报成功
                            this.updateById(studentGrade);
                        }
                    }
                }
            } catch (Exception e) {
            }
        }
    }

    @Override
    public Long getStudentReadingCount(Integer yearPart, Integer quarterNum, Long schoolId, Long subjectsId, Long studentId,Integer lessonType){
        return studentGradeMapper.getStudentReadingCount(yearPart,quarterNum,schoolId,subjectsId,studentId,lessonType);
    }

    @Override
    public IPage<StudentGrade> getStudentGradeLastList(IPage<?> page, Integer yearPart, Integer quarterNum, Long schoolId, Long subjectsId){
        return studentGradeMapper.getStudentGradeLastList(page,yearPart,quarterNum,schoolId,subjectsId);
    }

    @Override
    public StudentGrade getLastOne(Integer yearPart, Integer quarterNum, Long subjectsId, Long studentId, Integer lessonType){
        return studentGradeMapper.getLastOne(yearPart,quarterNum,subjectsId,studentId,lessonType);
    }



    @Override
    public void updateNotIsLast(Integer yearPart, Integer quarterNum){

        if (yearPart == null){
            Quarter quarterNow = iQuarterService.getNowQuarter();
            if (quarterNow != null){
                yearPart = quarterNow.getYearPart();
                quarterNum = quarterNow.getNum();
            }else {
                yearPart = 0;
                quarterNum = 0;
            }
        }

        List<StudentGrade> studentGradeList =  studentGradeMapper.getNotIsLastList(yearPart,quarterNum);
        for (StudentGrade studentGrade:studentGradeList){
            UpdateWrapper<StudentGrade> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("year_part",studentGrade.getYearPart());
            updateWrapper.eq("quarter_num",studentGrade.getQuarterNum());
            updateWrapper.eq("subjects_id",studentGrade.getSubjectsId());
            updateWrapper.eq("student_id",studentGrade.getStudentId());
            updateWrapper.eq("lesson_type",1);
            updateWrapper.set("is_last",0);
            studentGradeMapper.update(null,updateWrapper);
            studentGrade.setIsLast(1);
            studentGradeMapper.updateById(studentGrade);
        }
    }





    @Override
    public void studentClassGradePushMq(Integer yearPart, Integer quarterNum, Long schoolId, Long subjectsId){
        Quarter quarterNow = iQuarterService.getNowQuarter();
        if (yearPart!=null && quarterNum!=null){
            quarterNow.setYearPart(yearPart);
            quarterNow.setNum(quarterNum);
        }

        Integer pageSize =100;
        IPage<StudentGrade> iPage = new Page<>(1,pageSize);
        this.getStudentGradeLastList(iPage,quarterNow.getYearPart(),quarterNow.getNum(),schoolId,subjectsId);

        Long allPage = iPage.getPages();
        for (Integer i=1;i<=allPage;i++){
            iPage = new Page<>(i,pageSize);
            this.getStudentGradeLastList(iPage,quarterNow.getYearPart(),quarterNow.getNum(),schoolId,subjectsId);
            for (StudentGrade studentGrade:iPage.getRecords()){
                StudentClassType studentClassType = new StudentClassType();
                BeanUtils.copyProperties(studentGrade,studentClassType);
                Grade grade = iGradeService.getById(studentGrade.getGradeId());
                if (grade!=null){
                    studentClassType.setGradeId(grade.getId());
                    studentClassType.setGradeSection(grade.getYearClassId().getKey());
                    studentClassType.setTeacherId(grade.getTeacherId());
                    studentClassType.setSchoolId(grade.getSchoolId());
                    Staff staff = iStaffService.getById(grade.getTeacherId());
                    if (staff!=null){
                        studentClassType.setTeacherName(staff.getName());
                    }
                }
                iMqPushService.updateStudentClassType(studentClassType);
            }
        }
    }

    @Override
    public StudentGrade getLastForMaxId(Integer yearPart, Integer quarterNum, Long subjectsId, Long studentId, Integer lessonType,Integer yearClassId){
        return studentGradeMapper.getLastForMaxId(yearPart,quarterNum,subjectsId,studentId,lessonType,yearClassId);
    }
}
